// 添加更多日志
console.log('Content script loaded - Version 1.0');

// 检查 marked 是否正确加载
if (typeof marked === 'undefined') {
  console.error('Marked library not loaded');
} else {
  console.log('Marked library loaded successfully');
  // 配置 marked 选项
  marked.setOptions({
    breaks: true,  // 支持换行
    gfm: true,     // 支持 GitHub 风格 markdown
    sanitize: false // 允许 HTML 标签
  });
}

// 添加变量声明
let floatButton = null;

// 监听来自 background 和 popup 的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  console.log('Received message:', request);
  
  if (request.action === 'openDialog') {
    createAndShowDialog();
    sendResponse({ success: true });
  } else if (request.action === 'updateFloatButton') {
    console.log('Updating float button state:', request.isEnabled);
    try {
      if (request.isEnabled) {
        if (!floatButton) {
          floatButton = createFloatButton();
          document.body.appendChild(floatButton);
          console.log('Float button added to page');
        } else {
          console.log('Float button already exists');
        }
      } else {
        if (floatButton) {
          floatButton.remove();
          floatButton = null;
          console.log('Float button removed');
        } else {
          console.log('No float button to remove');
        }
      }
      sendResponse({ success: true });
    } catch (error) {
      console.error('Error updating float button:', error);
      sendResponse({ success: false, error: error.message });
    }
  }
  
  // 返回 true 表示会异步发送响应
  return true;
});

// 创建对话框
async function createDialog() {
  return new Promise((resolve) => {
    chrome.storage.local.get(['isLoggedIn', 'userToken', 'userName'], function(result) {
      console.log('Login state when creating dialog:', result);
      
      if (!result.isLoggedIn || !result.userToken) {
        console.log('User not logged in, showing login reminder');
        const loginReminder = createLoginReminderDialog();
        loginReminder.classList.add('global-window');
        resolve(loginReminder);
      } else {
        console.log('User logged in, creating normal dialog');
        const dialog = createNormalDialog(result.userName);
        dialog.classList.add('global-window');
        resolve(dialog);
      }
    });
  });
}

// 将原来的创建对话框逻辑移到这个函数中
function createNormalDialog(userName) {
  // 创建遮罩层
  const overlay = document.createElement('div');
  overlay.className = 'yinliai-overlay';
  document.body.appendChild(overlay);

  const dialog = document.createElement('div');
  dialog.className = 'yinliai-dialog';
  
  function showDialog() {
    // 检查显示方式
    chrome.storage.local.get(['windowStyle', 'isLoggedIn'], function(result) {
      const style = result.windowStyle || 'float';
      
      // 先检查登录状态
      if (!result.isLoggedIn) {
        hideDialog();
        createAndShowDialog(); // 重新创建对话框，会显示登录提示
        return;
      }
      
      if (style === 'dialog') {
        chrome.runtime.sendMessage({ action: 'openSidePanel' }, (response) => {
          if (!response || !response.success) {
            console.log('Failed to open side panel, falling back to floating window');
            fallbackToFloatingWindow();
          }
        });
      } else {
        showFloatingWindow();
      }
    });
  }

  function hideDialog() {
    if (chrome.sidePanel && chrome.sidePanel.close) {
      chrome.sidePanel.close();
    }
    if (overlay) {
      overlay.remove();
    }
    dialog.style.display = 'none';
  }

  function fallbackToFloatingWindow() {
    dialog.classList.remove('sidebar');
    overlay.style.display = 'block';
    dialog.style.display = 'block';
  }

  function showFloatingWindow() {
    dialog.classList.remove('sidebar');
    overlay.style.display = 'block';
    dialog.style.display = 'block';
  }

  // 设置显示方法
  dialog.show = showDialog;
  dialog.hide = hideDialog;

  // 获取快捷键并设置内容
  chrome.storage.local.get(['dialogShortcut', 'exploreShortcut'], function(result) {
    const exploreKey = result.exploreShortcut || 'Ctrl+Shift+E';
    const dialogKey = result.dialogShortcut || 'Ctrl+Shift+Y';

    dialog.innerHTML = `
      <div class="yinliai-dialog-header">
        <div class="yinliai-dialog-title">有什么问题尽管问我</div>
        <div class="yinliai-dialog-close">×</div>
      </div>
      <div class="yinliai-dialog-content">
        <div class="yinliai-dialog-input-section">
          <textarea class="yinliai-dialog-input" placeholder="输入您的问题..."></textarea>
          <button class="dialog-send-button">发送</button>
        </div>
        <div class="yinliai-dialog-middle-section">
          <div class="option-item">总结全文</div>
          <div class="option-item">解释当前屏幕</div>
        </div>
        <div class="yinliai-dialog-bottom-section">
          <div class="bottom-left">
            <div class="option-item visit-kimi">访问 YinliAI</div>
          </div>
          <div class="bottom-right">
            <span class="shortcut-key">${exploreKey}: 探索</span>
            <span class="shortcut-key">${dialogKey}: 对话</span>
          </div>
        </div>
      </div>
    `;

    // 在内容设置完成后绑定事件
    const closeButton = dialog.querySelector('.yinliai-dialog-close');
    const input = dialog.querySelector('.yinliai-dialog-input');
    const summaryButton = dialog.querySelector('.yinliai-dialog-middle-section .option-item:first-child');
    
    closeButton.addEventListener('click', () => {
      hideDialog(); // 只隐藏对话框，不删除登录状态
    });

    // 修改总结全文按钮点击事件
    summaryButton.addEventListener('click', async function() {
      const responseDiv = createResponseDiv();
      const contentDiv = responseDiv.querySelector('.response-content');
      const content = document.body.innerText;
      
      // 添加用户消息
      const userMessageDiv = document.createElement('div');
      userMessageDiv.className = 'chat-message user';
      userMessageDiv.innerHTML = `
        <div class="message-content">请帮我总结这篇文章的内容</div>
      `;
      contentDiv.appendChild(userMessageDiv);
      
      try {
        // 创建 AI 消息容器
        const messageDiv = document.createElement('div');
        messageDiv.className = 'chat-message ai';
        const messageContent = document.createElement('div');
        messageContent.className = 'message-content';
        messageDiv.appendChild(messageContent);
        
        // 显示加载动画
        messageContent.innerHTML = `
          <div class="typing-indicator">
            <div class="typing-dot"></div>
            <div class="typing-dot"></div>
            <div class="typing-dot"></div>
          </div>
        `;
        
        contentDiv.appendChild(messageDiv);
        contentDiv.scrollTop = contentDiv.scrollHeight;
        
        // 发送请求并处理流式响应
        const response = await sendChatRequest("请帮我总结这篇文章的内容：" + content);
        let fullText = '';
        
        for await (const chunk of streamResponse(response)) {
          fullText = chunk;
          messageContent.innerHTML = renderMarkdown(fullText);
          contentDiv.scrollTop = contentDiv.scrollHeight;
        }
        
        // 添加操作按钮
        const actionsDiv = document.createElement('div');
        actionsDiv.className = 'message-actions';
        actionsDiv.innerHTML = `
          <div class="action-button copy-button">复制</div>
          <div class="action-button regenerate-button">重新生成</div>
        `;
        messageDiv.appendChild(actionsDiv);
        
        // 绑定按钮事件
        const copyButton = actionsDiv.querySelector('.copy-button');
        const regenerateButton = actionsDiv.querySelector('.regenerate-button');
        
        copyButton.addEventListener('click', () => {
          navigator.clipboard.writeText(messageContent.textContent).then(() => {
            copyButton.textContent = '已复制';
            setTimeout(() => {
              copyButton.textContent = '复制';
            }, 1500);
          });
        });
        
        regenerateButton.addEventListener('click', async () => {
          messageContent.innerHTML = `
            <div class="typing-indicator">
              <div class="typing-dot"></div>
              <div class="typing-dot"></div>
              <div class="typing-dot"></div>
            </div>
          `;
          
          try {
            const newResponse = await sendChatRequest("请帮我总结这篇文章的内容：" + content);
            let newText = '';
            for await (const chunk of streamResponse(newResponse)) {
              newText = chunk;
              messageContent.innerHTML = renderMarkdown(newText);
              contentDiv.scrollTop = contentDiv.scrollHeight;
            }
          } catch (error) {
            messageContent.innerHTML = `
              <div class="error">生成失败，请重试</div>
            `;
          }
        });
        
      } catch (error) {
        const errorDiv = document.createElement('div');
        errorDiv.className = 'chat-message ai';
        errorDiv.innerHTML = `
          <div class="message-content error">抱歉，总结过程中出现错误，请稍后重试。</div>
        `;
        contentDiv.appendChild(errorDiv);
      }
    });

    // 修改输入框回车事件处理
    input.addEventListener('keypress', async function(e) {
      if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        const question = input.value.trim();
        if (question) {
          const responseDiv = createResponseDiv();
          await addMessage(question, true);
          input.value = '';
          
          try {
            const messageDiv = document.createElement('div');
            messageDiv.className = 'chat-message ai';
            const messageContent = document.createElement('div');
            messageContent.className = 'message-content';
            messageDiv.appendChild(messageContent);
            
            // 显示加载动画
            messageContent.innerHTML = `
              <div class="typing-indicator">
                <div class="typing-dot"></div>
                <div class="typing-dot"></div>
                <div class="typing-dot"></div>
              </div>
            `;
            
            const contentDiv = document.querySelector('.response-content');
            contentDiv.appendChild(messageDiv);
            
            // 添加平滑滚动到最新内容的函数
            function scrollToLatest(element, behavior = 'smooth') {
              const scrollHeight = element.scrollHeight;
              const clientHeight = element.clientHeight;
              const maxScroll = scrollHeight - clientHeight;
              
              element.scrollTo({
                top: maxScroll,
                behavior: behavior
              });
            }
            
            // 初始滚动到底部，使用即时滚动
            scrollToLatest(contentDiv, 'instant');
            
            // 发送请求并处理流式响应
            const response = await sendChatRequest(question);
            let fullText = '';
            
            // 创建一个防抖函数来处理滚动
            const debounce = (func, wait) => {
              let timeout;
              return function executedFunction(...args) {
                const later = () => {
                  clearTimeout(timeout);
                  func(...args);
                };
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
              };
            };

            // 创建一个防抖的滚动函数
            const debouncedScroll = debounce((element) => {
              scrollToLatest(element);
            }, 100);
            
            for await (const chunk of streamResponse(response)) {
              fullText = chunk;
              messageContent.innerHTML = renderMarkdown(fullText);
              // 使用防抖的滚动函数
              debouncedScroll(contentDiv);
            }
            
            // 添加操作按钮
            const actionsDiv = document.createElement('div');
            actionsDiv.className = 'message-actions';
            actionsDiv.innerHTML = `
              <div class="action-button copy-button">复制</div>
              <div class="action-button regenerate-button">重新生成</div>
            `;
            messageDiv.appendChild(actionsDiv);
            
            // 绑定按钮事件
            const copyButton = actionsDiv.querySelector('.copy-button');
            const regenerateButton = actionsDiv.querySelector('.regenerate-button');
            
            copyButton.addEventListener('click', () => {
              navigator.clipboard.writeText(messageContent.textContent).then(() => {
                copyButton.textContent = '已复制';
                setTimeout(() => {
                  copyButton.textContent = '复制';
                }, 1500);
              });
            });
            
            regenerateButton.addEventListener('click', async () => {
              messageContent.innerHTML = `
                <div class="typing-indicator">
                  <div class="typing-dot"></div>
                  <div class="typing-dot"></div>
                  <div class="typing-dot"></div>
                </div>
              `;
              
              try {
                const newResponse = await sendChatRequest(question);
                let newText = '';
                for await (const chunk of streamResponse(newResponse)) {
                  newText = chunk;
                  messageContent.innerHTML = renderMarkdown(newText);
                  contentDiv.scrollTop = contentDiv.scrollHeight;
                }
              } catch (error) {
                messageContent.innerHTML = `
                  <div class="error">生成失败，请重试</div>
                `;
              }
            });
            
          } catch (error) {
            await addMessage("抱歉，请求失败，请重试。", false);
          }
        }
      }
    });

    // 修改第二个弹窗的发送按钮点击事件处理函数，添加平滑滚动功能。
    const dialogSendButton = dialog.querySelector('.dialog-send-button');
    dialogSendButton.addEventListener('click', async () => {
      const question = input.value.trim();
      if (question) {
        const responseDiv = createResponseDiv();
        await addMessage(question, true);
        input.value = '';
        
        try {
          const messageDiv = document.createElement('div');
          messageDiv.className = 'chat-message ai';
          const messageContent = document.createElement('div');
          messageContent.className = 'message-content';
          messageDiv.appendChild(messageContent);
          
          // 显示加载动画
          messageContent.innerHTML = `
            <div class="typing-indicator">
              <div class="typing-dot"></div>
              <div class="typing-dot"></div>
              <div class="typing-dot"></div>
            </div>
          `;
          
          const contentDiv = document.querySelector('.response-content');
          contentDiv.appendChild(messageDiv);
          
          // 添加平滑滚动到最新内容的函数
          function scrollToLatest(element, behavior = 'smooth') {
            const scrollHeight = element.scrollHeight;
            const clientHeight = element.clientHeight;
            const maxScroll = scrollHeight - clientHeight;
            
            element.scrollTo({
              top: maxScroll,
              behavior: behavior
            });
          }
          
          // 初始滚动到底部，使用即时滚动
          scrollToLatest(contentDiv, 'instant');
          
          // 发送请求并处理流式响应
          const response = await sendChatRequest(question);
          let fullText = '';
          
          // 创建一个防抖函数来处理滚动
          const debounce = (func, wait) => {
            let timeout;
            return function executedFunction(...args) {
              const later = () => {
                clearTimeout(timeout);
                func(...args);
              };
              clearTimeout(timeout);
              timeout = setTimeout(later, wait);
            };
          };

          // 创建一个防抖的滚动函数
          const debouncedScroll = debounce((element) => {
            scrollToLatest(element);
          }, 100);
          
          for await (const chunk of streamResponse(response)) {
            fullText = chunk;
            messageContent.innerHTML = renderMarkdown(fullText);
            // 使用防抖的滚动函数
            debouncedScroll(contentDiv);
          }
            
            // 添加操作按钮
            const actionsDiv = document.createElement('div');
            actionsDiv.className = 'message-actions';
            actionsDiv.innerHTML = `
              <div class="action-button copy-button">复制</div>
              <div class="action-button regenerate-button">重新生成</div>
            `;
            messageDiv.appendChild(actionsDiv);
            
            // 绑定按钮事件
            const copyButton = actionsDiv.querySelector('.copy-button');
            const regenerateButton = actionsDiv.querySelector('.regenerate-button');
            
            copyButton.addEventListener('click', () => {
              navigator.clipboard.writeText(messageContent.textContent).then(() => {
                copyButton.textContent = '已复制';
                setTimeout(() => {
                  copyButton.textContent = '复制';
                }, 1500);
              });
            });
            
            regenerateButton.addEventListener('click', async () => {
              messageContent.innerHTML = `
                <div class="typing-indicator">
                  <div class="typing-dot"></div>
                  <div class="typing-dot"></div>
                  <div class="typing-dot"></div>
                </div>
              `;
              
              try {
                const newResponse = await sendChatRequest(question);
                let newText = '';
                for await (const chunk of streamResponse(newResponse)) {
                  newText = chunk;
                  messageContent.innerHTML = renderMarkdown(newText);
                  contentDiv.scrollTop = contentDiv.scrollHeight;
                }
              } catch (error) {
                messageContent.innerHTML = `
                  <div class="error">生成失败，请重试</div>
                `;
              }
            });
            
          } catch (error) {
            await addMessage("抱歉，请求失败，请重试。", false);
          }
      }
    });

    // 在内容设置完成后添加点击事件
    const visitButton = dialog.querySelector('.visit-kimi');
    visitButton.addEventListener('click', function() {
      window.open('https://ai.yinlimedia.com/creative/assistant/douyin', '_blank');
    });
  });

  document.body.appendChild(dialog);

  // 监听显示方式变化
  chrome.storage.onChanged.addListener(function(changes, namespace) {
    if (namespace === 'local' && changes.windowStyle) {
      const newStyle = changes.windowStyle.newValue;
      if (newStyle === 'dialog') {
        dialog.classList.add('sidebar');
      } else {
        dialog.classList.remove('sidebar');
      }
    }
  });

  // 点击遮罩层关闭
  overlay.addEventListener('click', () => {
    hideDialog(); // 只隐藏对话框，不删除登录状态
  });

  // ESC键关闭
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
      hideDialog(); // 只隐藏对话框，不删除登录状态
    }
  });

  return dialog;
}

// 修改登录提醒对话框的关闭逻辑
function createLoginReminderDialog() {
  const overlay = document.createElement('div');
  overlay.className = 'yinliai-overlay';
  document.body.appendChild(overlay);

  const loginReminder = document.createElement('div');
  loginReminder.className = 'yinliai-dialog';
  loginReminder.innerHTML = `
    <div class="yinliai-dialog-header">
      <div class="yinliai-dialog-title">请先登录</div>
      <div class="yinliai-dialog-close">×</div>
    </div>
    <div class="yinliai-dialog-content">
      <div class="login-reminder">
        <p>请点击右上角扩展图标登录后使用</p>
      </div>
    </div>
  `;
  
  document.body.appendChild(loginReminder);
  
  function hideReminder() {
    overlay.style.display = 'none';
    loginReminder.style.display = 'none';
  }
  
  loginReminder.show = () => {
    overlay.style.display = 'block';
    loginReminder.style.display = 'block';
  };
  
  loginReminder.hide = hideReminder;
  
  const closeButton = loginReminder.querySelector('.yinliai-dialog-close');
  closeButton.addEventListener('click', hideReminder);
  
  // 点击遮罩层关闭
  overlay.addEventListener('click', hideReminder);
  
  return loginReminder;
}

let dialogElement = null;

// 创建响应内容区域
function createResponseDiv() {
  // 先关闭之前的弹窗
  if (dialogElement) {
    dialogElement.hide();
  }

  // 移除之前的响应窗口（如果存在）
  const existingResponse = document.querySelector('.yinliai-response-container');
  if (existingResponse) {
    existingResponse.remove();
  }

  // 创建遮罩层
  const overlay = document.createElement('div');
  overlay.className = 'response-overlay';
  document.body.appendChild(overlay);

  const responseContainer = document.createElement('div');
  responseContainer.className = 'yinliai-response-container';
  
  responseContainer.innerHTML = `
    <div class="response-content-area">
      <div class="response-header">
        <div class="response-header-left">
          <img src="${chrome.runtime.getURL('images/loginL.png')}" alt="YinliAI" class="response-avatar">
          <span class="response-name">yinliai</span>
        </div>
        <div class="response-close">×</div>
      </div>
      <div class="response-content">
        <!-- 对话内容将在这里动态添加 -->
      </div>
    </div>
    <div class="response-input-area">
      <textarea class="response-input" placeholder="输入您的问题..."></textarea>
      <button class="response-send-button">发送</button>
    </div>
  `;
  
  document.body.appendChild(responseContainer);
  
  // 绑定输入和发送事件
  const input = responseContainer.querySelector('.response-input');
  const sendButton = responseContainer.querySelector('.response-send-button');
  const closeButton = responseContainer.querySelector('.response-close');
  
  function closeResponse() {
    responseContainer.remove();
    overlay.remove();
  }

  // 绑定关闭事件
  closeButton.addEventListener('click', closeResponse);
  overlay.addEventListener('click', closeResponse);

  // 发送按钮点击事件
  sendButton.addEventListener('click', async () => {
    const question = input.value.trim();
    if (question) {
      await addMessage(question, true);
      input.value = '';
      
      try {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'chat-message ai';
        const messageContent = document.createElement('div');
        messageContent.className = 'message-content';
        messageDiv.appendChild(messageContent);
        
        // 显示加载动画
        messageContent.innerHTML = `
          <div class="typing-indicator">
            <div class="typing-dot"></div>
            <div class="typing-dot"></div>
            <div class="typing-dot"></div>
          </div>
        `;
        
        const contentDiv = document.querySelector('.response-content');
        contentDiv.appendChild(messageDiv);
        contentDiv.scrollTop = contentDiv.scrollHeight;
        
        // 发送请求并处理流式响应
        const response = await sendChatRequest(question);
        let fullText = '';
        
        for await (const chunk of streamResponse(response)) {
          fullText = chunk; // 不累加文本，使用最新的 chunk
          messageContent.innerHTML = renderMarkdown(fullText);
          contentDiv.scrollTop = contentDiv.scrollHeight;
        }
        
        // 添加操作按钮
        const actionsDiv = document.createElement('div');
        actionsDiv.className = 'message-actions';
        actionsDiv.innerHTML = `
          <div class="action-button copy-button">复制</div>
          <div class="action-button regenerate-button">重新生成</div>
        `;
        messageDiv.appendChild(actionsDiv);
        
        // 绑定按钮事件
        const copyButton = actionsDiv.querySelector('.copy-button');
        const regenerateButton = actionsDiv.querySelector('.regenerate-button');
        
        copyButton.addEventListener('click', () => {
          navigator.clipboard.writeText(messageContent.textContent).then(() => {
            copyButton.textContent = '已复制';
            setTimeout(() => {
              copyButton.textContent = '复制';
            }, 1500);
          });
        });
        
        regenerateButton.addEventListener('click', async () => {
          messageContent.innerHTML = `
            <div class="typing-indicator">
              <div class="typing-dot"></div>
              <div class="typing-dot"></div>
              <div class="typing-dot"></div>
            </div>
          `;
          
          try {
            const newResponse = await sendChatRequest(question);
            let newText = '';
            for await (const chunk of streamResponse(newResponse)) {
              newText = chunk; // 不累加文本，使用最新的 chunk
              messageContent.innerHTML = renderMarkdown(newText);
              contentDiv.scrollTop = contentDiv.scrollHeight;
            }
          } catch (error) {
            messageContent.innerHTML = `
              <div class="error">生成失败，请重试</div>
            `;
          }
        });
        
      } catch (error) {
        await addMessage("抱歉，请求失败，请重试。", false);
      }
    }
  });

  // 回车发送
  input.addEventListener('keypress', async (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendButton.click();
    }
  });

  return responseContainer;
}

// 更新响应内容
function updateResponseContent(responseDiv, content) {
  const contentDiv = responseDiv.querySelector('.response-content');
  contentDiv.innerHTML = content;
}

// 模拟API响应
async function mockSummaryResponse(content) {
  await new Promise(resolve => setTimeout(resolve, 1000)); // 模拟延迟
  return `
    <div class="summary-section">
      <h3>全文摘要</h3>
      <p>111是110与112之间的自然数，具有丰富的数学性质，如是合数、写数、不寻常数等。其素因数分解为3×37，且在不同进制下有独特的表示方式。在科学上，111是钢的原子序数。在其他领域，111也与多事物相关，如香港过海隧道巴士111线、新西兰救援服务电话等。还被赋予一些文化意义。</p>
      <h3>关键段落</h3>
      <ul>
        <li>数学性质：111是第81个合数，正约数有1、3、37和111，素因数分解为3×37。</li>
        <li>写数与不寻常数：它是第84个写数，真约数和为41，写度为70。同时也是第76个不寻常数，大于平方根的素因数为37。</li>
        <li>科学领域：111是钢的原子序数。</li>
      </ul>
    </div>
  `;
}

// 修改 renderMarkdown 函数
function renderMarkdown(text) {
  try {
    if (typeof marked === 'undefined') {
      console.error('Marked library not loaded');
      return text;
    }
    
    if (typeof marked === 'object' && typeof marked.parse === 'function') {
      // 新版本的 marked 使用 parse 方法
      return marked.parse(text);
    } else if (typeof marked === 'function') {
      // 旧版本的 marked 直接作为函数调用
      return marked(text);
    }
    
    console.error('Marked library not properly initialized');
    return text;
  } catch (e) {
    console.error('Markdown parsing error:', e);
    return text;
  }
}

// 修改 streamResponse 函数，处理 SSE 数据和 think 标签
async function* streamResponse(response) {
  const reader = response.body.getReader();
  const decoder = new TextDecoder();

  // 创建一个MutationObserver来监听内容变化
  const contentDiv = document.querySelector('.response-content');
  if (contentDiv) {
    const observer = new MutationObserver((mutations) => {
      requestAnimationFrame(() => {
        const isNearBottom = contentDiv.scrollHeight - contentDiv.scrollTop - contentDiv.clientHeight < 100;
        if (isNearBottom) {
          contentDiv.scrollTo({
            top: contentDiv.scrollHeight,
            behavior: 'smooth'
          });
        }
      });
    });

    observer.observe(contentDiv, {
      childList: true,
      subtree: true,
      characterData: true
    });
  }

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    
    const text = decoder.decode(value);
    const lines = text.split('\n');
    
    for (const line of lines) {
      if (line.startsWith('data: ')) {
        try {
          const jsonStr = line.slice(6); // 移除 "data: " 前缀
          if (jsonStr === '[DONE]') continue;
          
          const parsed = JSON.parse(jsonStr);
          if (parsed.code === 990 && parsed.data) {
            // 移除 think 标签
            const cleanedData = parsed.data.replace(/<think>\n?/g, '').replace(/<\/think>/g, '');
            yield cleanedData;
          }
        } catch (e) {
          console.error('Parse error:', e);
        }
      }
    }
  }
}

async function sendChatRequest(prompt) {
  // 使用代理 URL
  const proxyUrl = chrome.runtime.getURL('proxy');
  const targetUrl = 'https://ai.yinlimedia.com/ai/creativeCenter/deepseekR1';
  
  const response = await fetch(targetUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json,text/event-stream',
      'Authorization': await getUserToken(),
      'Origin': chrome.runtime.getURL(''),
      'X-Requested-With': 'XMLHttpRequest'
    },
    body: JSON.stringify({
      "user_prompt": prompt,
      "is_online": true,
      "user_info": {
        "id": 583,
        "version": 1
      }
    }),
    mode: 'cors',
    credentials: 'include'
  });

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }

  return response;
}

// 获取用户 token
function getUserToken() {
  return new Promise((resolve) => {
    chrome.storage.local.get(['userToken'], function(result) {
      resolve(result.userToken);
    });
  });
}

// 修改消息显示函数
async function addMessage(content, isUser = false) {
  const contentDiv = document.querySelector('.response-content');
  const messageDiv = document.createElement('div');
  messageDiv.className = `chat-message ${isUser ? 'user' : 'ai'}`;
  
  if (isUser) {
    // 用户消息不需要 markdown 渲染
    messageDiv.innerHTML = `
      <div class="message-content">${content}</div>
    `;
  } else {
    // AI 消息需要 markdown 渲染
    messageDiv.innerHTML = `
      <div class="message-content">${renderMarkdown(content)}</div>
    `;
  }
  
  contentDiv.appendChild(messageDiv);
  contentDiv.scrollTop = contentDiv.scrollHeight;
}

// 修改消息处理函数
async function handleResponse(response, messageContent, contentDiv) {
  let fullText = '';
  for await (const chunk of streamResponse(response)) {
    fullText += chunk;
    messageContent.innerHTML = renderMarkdown(fullText);
    contentDiv.scrollTop = contentDiv.scrollHeight;
  }
}

async function createAndShowDialog() {
  try {
    console.log('Creating and showing dialog...');
    
    if (!dialogElement) {
      console.log('Creating new dialog element');
      dialogElement = await createDialog();
    }
    
    // 创建遮罩层
    const overlay = document.createElement('div');
    overlay.className = 'global-overlay';
    document.body.appendChild(overlay);
    
    // 确保对话框已添加到 DOM
    if (!document.body.contains(dialogElement)) {
      console.log('Adding dialog to DOM');
      document.body.appendChild(dialogElement);
    }
    
    // 设置初始样式
    dialogElement.style.display = 'flex';
    
    // 使用 requestAnimationFrame 确保过渡效果生效
    requestAnimationFrame(() => {
      console.log('Showing dialog with animation');
      overlay.classList.add('show');
      dialogElement.classList.add('show');
      
      // 聚焦输入框
      const input = dialogElement.querySelector('.yinliai-dialog-input');
      if (input) {
        input.focus();
      }
    });
    
    // 添加关闭处理
    function closeDialog() {
      console.log('Closing dialog');
      overlay.classList.remove('show');
      dialogElement.classList.remove('show');
      
      setTimeout(() => {
        overlay.remove();
        dialogElement.style.display = 'none';
      }, 300);
    }
    
    // 更新关闭事件监听
    const closeButton = dialogElement.querySelector('.yinliai-dialog-close');
    if (closeButton) {
      closeButton.onclick = closeDialog;
    }
    
    // 点击遮罩层关闭
    overlay.onclick = (e) => {
      if (e.target === overlay) {
        closeDialog();
      }
    };
    
    // ESC 键关闭
    const escHandler = (e) => {
      if (e.key === 'Escape') {
        closeDialog();
      }
    };
    document.addEventListener('keydown', escHandler);
    
    // 将关闭方法添加到对话框对象
    dialogElement.hide = closeDialog;
    
    console.log('Dialog setup complete');
  } catch (error) {
    console.error('Error showing dialog:', error);
  }
}

// 修改初始化函数
function initialize() {
  console.log('Initializing content script...');
  
  // 检查悬浮按钮状态
  chrome.storage.local.get(['floatButtonEnabled'], function(result) {
    console.log('Initial float button state:', result);
    
    if (result.floatButtonEnabled) {
      console.log('Float button should be enabled, creating...');
      if (!floatButton) {
        try {
          floatButton = createFloatButton();
          document.body.appendChild(floatButton);
          console.log('Float button created and added to page');
        } catch (error) {
          console.error('Error creating float button:', error);
        }
      } else {
        console.log('Float button already exists');
      }
    } else {
      console.log('Float button is disabled');
    }
  });
}

// 立即执行初始化
initialize();

// 修改悬浮按钮的点击事件处理
function createFloatButton() {
  console.log('Creating float button...');
  
  const button = document.createElement('div');
  button.id = 'yinliai-float-button';
  button.className = 'yinliai-float-button';
  
  // 创建图片元素
  const img = document.createElement('img');
  // 使用登录用户的头像或默认头像
  chrome.storage.local.get(['userAvatar'], function(result) {
    img.src = result.userAvatar || chrome.runtime.getURL('images/avatar.png');
    console.log('Float button icon URL:', img.src);
  });
  img.alt = 'YinliAI';
  img.draggable = false;
  img.style.cssText = `
    width: 30px;
    height: 30px;
    border-radius: 50%;
    object-fit: cover;
  `;
  
  button.appendChild(img);
  
  // 设置初始位置和样式
  button.style.cssText = `
    position: fixed;
    width: 36px;
    height: 36px;
    right: 20px;
    bottom: 20px;
    z-index: 2147483647;
    background: white;
    border-radius: 50%;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s;
    border: 2px solid #2563EB;
    padding: 2px;
  `;
  
  // 修改点击事件处理
  button.addEventListener('click', async function(e) {
    console.log('Float button clicked');
    if (!isDragging) {
      e.preventDefault();
      e.stopPropagation();
      
      // 检查登录状态
      chrome.storage.local.get(['isLoggedIn', 'userToken'], function(result) {
        console.log('Checking login state:', result);
        
        if (!result.isLoggedIn || !result.userToken) {
          console.log('User not logged in, showing login reminder');
          // 打开 popup 页面进行登录
          chrome.runtime.sendMessage({ action: 'openPopup' });
        } else {
          console.log('User logged in, showing first dialog');
          // 打开第一层对话框
          createAndShowDialog();
        }
      });
    }
  });
  
  // 拖拽功能
  let isDragging = false;
  let startX, startY;
  
  button.addEventListener('mousedown', function(e) {
    console.log('Float button mouse down');
    if (e.button !== 0) return;
    isDragging = false;
    startX = e.clientX - button.offsetLeft;
    startY = e.clientY - button.offsetTop;
    
    const mouseMoveHandler = function(e) {
      isDragging = true;
      const x = e.clientX - startX;
      const y = e.clientY - startY;
      button.style.left = `${x}px`;
      button.style.top = `${y}px`;
      button.style.right = 'auto';
      button.style.bottom = 'auto';
    };
    
    const mouseUpHandler = function() {
      console.log('Float button mouse up');
      document.removeEventListener('mousemove', mouseMoveHandler);
      document.removeEventListener('mouseup', mouseUpHandler);
      setTimeout(() => {
        isDragging = false;
      }, 10);
    };
    
    document.addEventListener('mousemove', mouseMoveHandler);
    document.addEventListener('mouseup', mouseUpHandler);
  });
  
  // 添加悬浮效果
  button.addEventListener('mouseenter', function() {
    button.style.transform = 'scale(1.1)';
    button.style.boxShadow = '0 6px 16px rgba(0, 0, 0, 0.2)';
  });
  
  button.addEventListener('mouseleave', function() {
    button.style.transform = 'scale(1)';
    button.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';
  });
  
  console.log('Float button created successfully');
  return button;
}